package com.jbit.hxy.config;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.jbit.hxy.properties.WxPayProperties;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(WxPayService.class)
public class WechatPayConfig {

    @Resource
    private WxPayProperties wxPayProperties;

    /**
     * 微信支付服务Bean
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public WxPayService wxPayService() {
        WxPayConfig wxPayConfig = new WxPayConfig();
        /**
         * 配置AppId
         */
        wxPayConfig.setAppId(StringUtils.trimToNull(wxPayProperties.getAppId()));
        /**
         * 配置商户号
         */
        wxPayConfig.setMchId(StringUtils.trimToNull(wxPayProperties.getMchId()));
        /**
         * 配置商户密钥
         */
        wxPayConfig.setMchKey(StringUtils.trimToNull(wxPayProperties.getMchKey()));

        /**
         * 配置支付回调地址
         */
        wxPayConfig.setNotifyUrl(StringUtils.trimToNull(wxPayProperties.getNotifyUrl()));


        /**
         * 申请退款相关配置项
         */

        wxPayConfig.setKeyPath(StringUtils.trimToNull(wxPayProperties.getKeyPath()));
        wxPayConfig.setPrivateKeyPath(StringUtils.trimToNull(wxPayProperties.getPrivateKeyPath()));
        wxPayConfig.setPrivateCertPath(StringUtils.trimToNull(wxPayProperties.getPrivateCertPath()));


        /**
         * 配置是否使用沙箱环境
         */
        wxPayConfig.setUseSandboxEnv(false);
        /**
         *  配置签名类型(支持HMAC-SHA256和MD5)
         */
        wxPayConfig.setSignType(WxPayConstants.SignType.MD5);
        /**
         *  构建微信支付服务类
         */
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig);
        return wxPayService;
    }
}
